﻿#if NET35
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Kernelx.Common.DataAnnotations
{
    /// <summary>
    /// 
    /// </summary>
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
    public class RangeAttribute : ValidationAttribute
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="minimum"></param>
        /// <param name="maximum"></param>
        public RangeAttribute(double minimum, double maximum) { Minimum = minimum; Maximum = maximum; OperandType = typeof(double); }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="minimum"></param>
        /// <param name="maximum"></param>
        public RangeAttribute(int minimum, int maximum) { Minimum = minimum; Maximum = maximum; OperandType = typeof(int); }

        /// <summary>
        /// 
        /// </summary>
        public object Maximum { get; }
        /// <summary>
        /// 
        /// </summary>
        public object Minimum { get; }
        /// <summary>
        /// 
        /// </summary>
        public Type OperandType { get; }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="value"></param>
        /// <param name="validationContext"></param>
        /// <returns></returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //todo: 验证逻辑带完善

            if (value != null)
            {
                if (OperandType == typeof(double))
                {
                    var min = (double)Minimum;
                    var max = (double)Maximum;
                    var v = (double)value;
                    if (v < min || v > max)
                        return new ValidationResult($"的范围必须在{Minimum}和{Maximum}之间");
                }
                else
                {
                    var min = (int)Minimum;
                    var max = (int)Maximum;
                    var f = value.GetType() == typeof(int);
                    var v = f ? (int)value : value.ToString().Length;
                    if (v < min || v > max)
                        return new ValidationResult($"的{(f ? "范围" : "长度")}必须在{Minimum}和{Maximum}之间");
                }
            }

            return null;

        }
    }
}

#endif